<?php

class cronActions extends sfActions {

    public function preExecute() {
        date_default_timezone_set(AppTools::TIMEZONE);
    }

    public function executeTest(sfWebRequest $request) {
        $time = microtime(true);

//        echo AppTools::getDbTime();

        $time = microtime(true) - $time;
        echo $time;
        die();
    }

    private static function startLog($action, $ip) {
        $log = new LogCron();
        $log->action = $action;
        $log->ip = $ip;
        $log->save();
        return $log;
    }

    public function executeInventory(sfWebRequest $request) {
        $ip = $request->getRemoteAddress();
        $action = $request->getPathInfo();
        $log = self::startLog($action, $ip);

        $yesterday = date('Y-m-d', strtotime("-1 days"));
        $today = date('Y-m-d');
        $invItems = InventoryTable::getByDate($yesterday);

        if (count($invItems)) {
            $i = 0;
            $values = array();
            $sql = 'INSERT INTO `inventory` (inv_date, store_id, user_id, product_id, qty_first, qty_last, qty_in, qty_out) VALUES ';
            $pdo = Doctrine_Manager::connection()->getDbh();
            foreach ($invItems as $item) {
                if (++$i > 500) {
                    $pdo->exec($sql . implode(",\n", $values));
                    $i = 0;
                    $values = array();
                }
                $values[] = "('$today', {$item['store_id']}, {$item['user_id']}, {$item['product_id']}, {$item['qty_last']}, {$item['qty_last']}, 0, 0)";
            }
            $pdo->exec($sql . implode(",\n", $values));
        }

        $log->completed_at = date('Y-m-d H:i:s');
        $log->save();
        die();
    }

}
